package controller

import (
	"github.com/gin-gonic/gin"
	"ylm.sl/common/convention/results"
	"ylm.sl/global"
	"ylm.sl/internal/api/request"
	"ylm.sl/internal/service"
)

type ShortLinkController struct {
	service service.IShortLinkService
}

func (c *ShortLinkController) CreateShortLink(context *gin.Context) {
	var requestParam request.ShortLinkCreateReqDTO

	err := context.ShouldBindJSON(&requestParam)
	if err != nil {
		global.Log.ErrContext(context, "Short link create request fail %v", err)
		results.Failure(context)
		return
	}
	resp, err := c.service.CreateShortLink(context, &requestParam)
	if err != nil {
		results.Failure(context)
		return
	}
	results.SuccessWithData(context, *resp)

}

func (c *ShortLinkController) CreateShortLinkByLock(context *gin.Context) {
	var requestParam request.ShortLinkCreateReqDTO

	err := context.ShouldBindJSON(&requestParam)
	if err != nil {
		global.Log.ErrContext(context, "Short link create request fail %v", err)
		results.Failure(context)
		return
	}
	resp, err := c.service.CreateShortLinkByLock(context, &requestParam)
	if err != nil {
		results.Failure(context)
		return
	}
	results.SuccessWithData(context, *resp)
}

func (c *ShortLinkController) BatchCreateShortLink(context *gin.Context) {
	var requestParam request.ShortLinkBatchCreateReqDTO
	err := context.ShouldBindJSON(&requestParam)
	if err != nil {
		global.Log.ErrContext(context, "Short link batch create request fail %v", err)
		results.Failure(context)
		return
	}
	resp, err := c.service.BatchCreateShortLink(context, &requestParam)
	if err != nil {
		results.Failure(context)
		return
	}
	results.SuccessWithData(context, *resp)

}

func (c *ShortLinkController) UpdateShortLink(context *gin.Context) {
	var requestParam request.ShortLinkUpdateReqDTO
	err := context.ShouldBindJSON(&requestParam)
	if err != nil {
		global.Log.ErrContext(context, "Short link batch create request fail %v", err)
		results.Failure(context)
		return
	}
	err := c.service.UpdateShortLink(context, &requestParam)
	if err != nil {
		results.Failure(context)
		return
	}
	results.Success(context)
}

func NewShortLinkController(service service.IShortLinkService) *ShortLinkController {
	return &ShortLinkController{service: service}
}
